﻿using CleanArchitecture.Core.Handlers;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Infrastructure.Entities.Settings;
using CleanArchitecture.Infrastructure.Interfaces;
using System;

namespace CleanArchitecture.Web.WebStartupTasks
{
    public class WebStartUpTask : IStartupTask
    {
        private IWebHelper _webHelper;
        /// <summary>
        /// Executes a task
        /// DavidLee 2020/05/13 Linux踩坑，windows和Linux平台在时间区域定义有所不同
        /// </summary>
        public void Execute()
        {
            try
            {
                //DavidLee 2019/11/24
                //获取并存储服务器运行http地址
                bool saveSetting = false;
                var commonSettings = EngineContext.Current.Resolve<CommonSettings>();
                if (string.IsNullOrEmpty(commonSettings.ServerUrl))
                {
                    _webHelper = EngineContext.Current.Resolve<IWebHelper>();
                    commonSettings.ServerUrl = _webHelper.GetServerLocation();
                    saveSetting = true;
                }
                if (string.IsNullOrEmpty(commonSettings.DefaultTimeZoneId))
                {
                    commonSettings.DefaultTimeZoneId = TimeZoneInfo.Local.Id;
                    saveSetting = true;
                }
                var datetimeHelper = EngineContext.Current.Resolve<IDateTimeHelper>();
                if (datetimeHelper.FindTimeZoneById(commonSettings.DefaultTimeZoneId) == null)
                {
                    commonSettings.DefaultTimeZoneId = TimeZoneInfo.Local.Id;
                    saveSetting = true;
                }
                if (saveSetting)
                    //EngineContext.Current.Resolve<ISettingService>().SaveSetting(commonSettings, setting => setting.ServerUrl, clearCache: true);
                    EngineContext.Current.Resolve<ISettingService>().SaveSetting(commonSettings);
            }
            catch(TimeZoneNotFoundException tzex)
            {

            }
        }

        /// <summary>
        /// Gets order of this startup task implementation
        /// </summary>
        public int Order => 2;
         
    }
}
